package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.*;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.Constant;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.*;

/**
 * 描述 : 工单产品action
 * 作者 : zdl
 * 日期 : 2017/7/12 11:25
 */
public class JobProductAction extends BaseActionSupport {
    private static final long serialVersionUID = 6573408722169724089L;
    /**
     * 工单接口
     */
    @Autowired
    private IJobService jobServiceImpl;
    /**
     * 客户接口
     */
    @Autowired
    private ICustomerService customerServiceImpl;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 工单产品接口
     */
    @Autowired
    private IJobProductService jobProductServiceImpl;
    /**
     * 工单产品处理历史接口
     */
    @Autowired
    private IJobProductHistoryService jobProductHistoryServiceImpl;
    /**
     * 产品接口
     */
    @Autowired
    private IProductService productServiceImpl;

    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(JobProductAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private JobProduct jobProduct;
    private Job job;
    private String dealName;
    private String stateStr;
    private String type;
    private List<JobProductHistory> jphList = new ArrayList<>();

    /**
     * 获取工单产品列表
     *
     * @return json
     */
    public String getJobProductList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<JobProduct> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = jobProductServiceImpl.pageByJobProduct(pageInfo, jobProduct);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<JobProduct> jpList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> jpMapList = new ArrayList<>();
                if (jpList != null && !jpList.isEmpty() && jpList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (JobProduct jp : jpList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", jp.getId());
                        String jobCode = "";
                        String jobId = jp.getJobId();
                        if (StringUtils.isNotBlank(jobId)) {
                            Job j = jobServiceImpl.getJobById(jobId);
                            if (j != null) {
                                jobCode = StringUtils.defaultString(j.getCode(), "");
                            }
                        }
                        map.put("jobCode", jobCode);
                        String productTypeStr = "";
                        String productName = "";
                        String outTime = "";
                        String productCode = jp.getProductCode();
                        if (StringUtils.isNotBlank(productCode)) {
                            Product p = productServiceImpl.getProductByCode(productCode);
                            if (p != null) {
                                productTypeStr = dictServiceImpl.getDictByValueAndType(p.getProductType(), Constant.PRODUCT_TYPE);
                                productName = StringUtils.defaultString(p.getName(), "");
                                if (p.getStockState() == 1) {
                                    outTime = StringUtils.defaultString(p.getOutOrInTime(), "");
                                }
                            }
                        }
                        map.put("productTypeStr", productTypeStr);
                        map.put("productCode", productCode);
                        map.put("productName", productName);
                        map.put("outTime", outTime);
                        map.put("problem", StringUtils.defaultString(jp.getProblem(), ""));
                        map.put("dealTime", StringUtils.defaultString(jp.getDealTime(), ""));
                        Integer state = jp.getState();
                        map.put("jpState", state);
                        String stateStr = getStateStr(state);
                        map.put("stateStr", stateStr);
                        jpMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", jpMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改/详情页面
     *
     * @return type
     */
    @SuppressWarnings("all")
    public String toUpdateOrDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                jobProduct = jobProductServiceImpl.getJobProductById(id);
                jphList = jobProductHistoryServiceImpl.listJobProductHistoryByJpId(id);
                if (jobProduct != null) {
                    String jobId = jobProduct.getJobId();
                    if (StringUtils.isNotBlank(jobId)) {
                        job = jobServiceImpl.getJobById(jobId);
                    }
                    String dealId = jobProduct.getDealId();
                    if (StringUtils.isNotBlank(dealId)) {
                        User u = userServiceImpl.getUserById(dealId);
                        if (u != null) {
                            dealName = StringUtils.defaultString(u.getUserName(), "");
                        }
                    }
                    Integer state = jobProduct.getState();
                    stateStr = getStateStr(state);
                    if (type.equals("update")) {
                        return "update";
                    } else if (type.equals("detail")) {
                        return "detail";
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 成功标识
     */
    public String saveJobProduct() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && jobProduct != null) {
                String jpId = BaseTool.getPK();
                Integer state = jobProduct.getState();
                String stateStr = "";
                if (state == 0) {
                    stateStr = "受理";
                } else if (state == 1) {
                    stateStr = "派发";
                } else if (state == 2) {
                    stateStr = "办结";
                }
                String nowTime = TimeTool.getNowTime();
                String userName = loginUser.getUserName();
                String comCode = loginUser.getComCode();
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    jobProduct.setId(jpId);
                    jobProduct.setDealTime(TimeTool.getNowTime());
                    if (StringUtils.isNotBlank(userName)) {
                        jobProduct.setCreateUserId(loginUser.getId());
                        jobProduct.setCreateUserName(userName);
                    }
                    if (StringUtils.isNotBlank(comCode)) {
                        jobProduct.setComCode(comCode);
                    }
                    jobProductServiceImpl.saveJobProduct(jobProduct);
                    out.print("success");
                    //添加系统日志
                    String content = "用户：" + userName + "，于" + nowTime + " " + stateStr + "工单问题产品：" + jobProduct.getProductCode() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "工单管理", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    jpId = jobProduct.getId();
                    JobProduct oldJp = jobProductServiceImpl.getJobProductById(jpId);
                    if (oldJp != null) {
                        oldJp.setProductCode(jobProduct.getProductCode());
                        oldJp.setProblem(jobProduct.getProblem());
                        oldJp.setDealId(jobProduct.getDealId());
                        oldJp.setState(jobProduct.getState());
                        oldJp.setSolution(jobProduct.getSolution());
                        if (StringUtils.isNotBlank(userName)) {
                            oldJp.setUpdateUserId(loginUser.getId());
                            oldJp.setUpdateUserName(userName);
                        }
                        jobProductServiceImpl.updateJobProduct(oldJp);
                        out.print("success");
                        //添加系统日志
                        String content = "用户：" + userName + "，于" + nowTime + " " + stateStr + "工单问题产品：" + oldJp.getProductCode() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "工单管理", 2, content, logServiceImpl);
                    }
                }
                //添加处理历史记录
                JobProductHistory jph = new JobProductHistory();
                jph.setId(BaseTool.getPK());
                jph.setJpId(jpId);
                String dealId = jobProduct.getDealId();
                String dealName = "";
                if (StringUtils.isNotBlank(dealId)) {
                    User u = userServiceImpl.getUserById(dealId);
                    if (u != null) {
                        dealName = StringUtils.defaultString(u.getUserName(), "");
                    }
                }
                String dealInfo = "";
                if (state == 0) {
                    dealInfo = stateStr + "：" + userName + "，于" + nowTime + stateStr;
                } else if (state == 1) {
                    dealInfo = stateStr + "：" + userName + "，于" + nowTime + stateStr + "给" + dealName;
                } else if (state == 2) {
                    dealInfo = stateStr + "：" + userName + "，于" + nowTime + stateStr + "，解决方案：" + jobProduct.getSolution();
                }
                jph.setDealInfo(dealInfo);
                jph.setDealName(dealName);
                jph.setCreateUserId(loginUser.getId());
                jph.setCreateUserName(userName);
                jph.setComCode(comCode);
                jobProductHistoryServiceImpl.saveJobProductHistory(jph);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }


    /**
     * 获取处理状态
     *
     * @param state 状态值
     * @return 状态名称
     */
    private String getStateStr(Integer state) {
        String stateStr = "";
        if (state != null) {
            switch (state) {
                case 0:
                    stateStr = "已受理";
                    break;
                case 1:
                    stateStr = "已派发";
                    break;
                case 2:
                    stateStr = "已办结";
                    break;
                default:
                    break;
            }
        }
        return stateStr;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public JobProduct getJobProduct() {
        return jobProduct;
    }

    public void setJobProduct(JobProduct jobProduct) {
        this.jobProduct = jobProduct;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Job getJob() {
        return job;
    }

    public void setJob(Job job) {
        this.job = job;
    }

    public String getDealName() {
        return dealName;
    }

    public void setDealName(String dealName) {
        this.dealName = dealName;
    }

    public String getStateStr() {
        return stateStr;
    }

    public void setStateStr(String stateStr) {
        this.stateStr = stateStr;
    }

    public List<JobProductHistory> getJphList() {
        return jphList;
    }

    public void setJphList(List<JobProductHistory> jphList) {
        this.jphList = jphList;
    }
}
